const { Controller } = require('egg');
const jwt = require('jsonwebtoken');
class UserController extends Controller {
  async login() {
    const { username, password, captcha } = this.ctx.request.body;
    await this.ctx.service.user.login(username, password, captcha);
  }

  async register() {
    const { username, password } = this.ctx.request.body;
    this.ctx.body = await this.ctx.service.user.register(username, password);
  }
  // 刷新 Token
  async refresh() {
    const { ctx, app } = this;
    const { refreshToken } = ctx.request.body;
    try {
      const payload = jwt.verify(refreshToken, app.config.jwt.refreshSecret);
      const newToken = jwt.sign(
        {
          uid: payload.uid,
          username: payload.username,
        },
        app.config.jwt.secret,
        { expiresIn: app.config.jwt.expiresIn },
      );
      ctx.body = { token: newToken };
    } catch {
      ctx.throw(401, '刷新令牌无效');
    }
  }
  async captcha() {
    const captcha = await this.ctx.service.verify.getCaptcha();
    this.ctx.session.captcha = captcha.text;
    console.log(this.ctx.session.captcha);
    this.ctx.type = 'image/svg+xml';
    this.ctx.body = captcha.data;
  }
}

module.exports = UserController;
